package com.sicnu.cheer.leaugebar.eventmodule.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.bean.EventBean;
import com.sicnu.cheer.generalmodule.bean.LeagueBean;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.generalmodule.util.NetWorkUtil;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.generalmodule.widget.NoDoubleClickListener;
import com.sicnu.cheer.leaugebar.eventmodule.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;
import io.github.lijunguan.imgselector.ImageSelector;

public class LaunchEventActivity extends BaseActivity implements View.OnClickListener{

    private EditText titleET;
    private EditText contentET;
    private TextView countTV;
    private ImageView attachIV;
    private String attachmentPath="";
    private ProgressDialog progressDialog;

    private LeagueBean leagueBean;
    @Override
    public int getContentViewId() {
        return R.layout.activity_launch_event;
    }

    @Override
    protected void initView() {
        super.initView();
        ((TextView) findViewById(R.id.title)).setText("新建活动");
        findViewById(R.id.back).setOnClickListener(this);
        titleET = ((EditText) findViewById(R.id.event_title_et));
        contentET = ((EditText) findViewById(R.id.event_content_et));
        countTV = ((TextView) findViewById(R.id.character_count_tv));
        contentET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
            @Override
            public void afterTextChanged(Editable s) {
                countTV.setText(contentET.getText().toString().length()+"/300");
            }
        });
        attachIV = ((ImageView) findViewById(R.id.attachment_iv));
        attachIV.setOnClickListener(this);
        findViewById(R.id.launch_event_submit_btn).setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onClick(View v) {
                super.onClick(v);
                if (leagueBean==null){
                    UIHelper.ToastMessage(mThis,"请设置您当前所在社团");
                }else {
                    CheckAndSubmit();
                }
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        progressDialog = new ProgressDialog(mThis);
        progressDialog.setMessage("加载中...");
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        MyUser currentUser = MyUser.getCurrentUser(mThis, MyUser.class);
        if (currentUser.getLeague()!=null) {
            BmobQuery<LeagueBean> query = new BmobQuery<>();
            query.addWhereEqualTo("objectId", currentUser.getLeague().getObjectId());
            query.findObjects(mThis, new FindListener<LeagueBean>() {
                @Override
                public void onSuccess(List<LeagueBean> list) {
                    if (list != null && list.size() >= 0) {
                        leagueBean = list.get(0);
                    }
                }

                @Override
                public void onError(int i, String s) {

                }
            });
        }

    }

    /**
     * 检测输入合法性并提交
     */
    private void CheckAndSubmit() {
        final String title=titleET.getText().toString().trim();
        final String content=contentET.getText().toString().trim();
        if (StringUtils.isEmpty(title)){
            UIHelper.ToastMessage(mThis,"请填写活动标题");
            return;
        }
        if (StringUtils.isEmpty(content)){
            UIHelper.ToastMessage(mThis,"请输入活动内容");
            return;
        }
        if (!NetWorkUtil.isConnect(mThis)){
            UIHelper.ToastMessage(mThis,"没有网络，请设置！");
            return;
        }
        progressDialog.show();
        final BmobFile bmobFile = new BmobFile(new File(attachmentPath));
        bmobFile.uploadblock(this, new UploadFileListener() {
            @Override
            public void onSuccess() {
                EventBean eventBean = new EventBean();
                MyUser currentUser = MyUser.getCurrentUser(mThis, MyUser.class);
                eventBean.setAuthor(currentUser);
                eventBean.setLeague(leagueBean);
                eventBean.setTitle(title);
                eventBean.setContent(content);
                eventBean.setImageUrl(bmobFile.getFileUrl(mThis));
                eventBean.setViews(0);
                eventBean.setLikesInt(0);
                eventBean.setOn(true);
                eventBean.save(mThis, new SaveListener() {
                    @Override
                    public void onSuccess() {
                        dismissProgress();
                        UIHelper.ToastMessage(mThis,"活动创建成功");
                        finish();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        dismissProgress();
                        UIHelper.ToastMessage(mThis,"活动创建失败："+s);
                    }
                });
            }

            @Override
            public void onProgress(Integer arg0) {
            }

            @Override
            public void onFailure(int arg0, String arg1) {
                dismissProgress();
                UIHelper.ToastMessage(mThis,"上传文件失败:" + arg0+",msg = "+arg1);
            }
        });

    }

    private void dismissProgress() {
        if (progressDialog!=null&&progressDialog.isShowing()){
            progressDialog.dismiss();
        }
    }


    @Override
    public void onClick(View v) {
        if (v.getId()==R.id.back){
            onBackPressed();
        }else if (v.getId()==R.id.attachment_iv){
            ImageSelector.getInstance()
                    .setSelectModel(ImageSelector.MULTI_MODE)
                    .setMaxCount(1)
                    .setGridColumns(3)
                    .setShowCamera(true)
                    .setToolbarColor(getResources().getColor(R.color.theme_green_color))
                    .startSelect(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.REQUEST_SELECT_IMAGE
                && resultCode == RESULT_OK) {
            ArrayList<String> imagesPath = data.getStringArrayListExtra(ImageSelector.SELECTED_RESULT);
            if (imagesPath != null) {
                attachmentPath = imagesPath.get(0);
                Glide.with(mThis).load(attachmentPath).placeholder(R.drawable.placeholder).into(attachIV);
            }
        }
    }
}
